package com.example.springsecurity05.service;

import com.example.springsecurity05.dao.UserDao;
import com.example.springsecurity05.entity.Role;
import com.example.springsecurity05.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserDao userDao;

//    private final UserDao userDao;
//
//    public MyUserDetailService(UserDao userDao) {
//        this.userDao = userDao;
//    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        UserDetails user = User.withUsername("root").password("{noop}123").roles("admin").build();
//        return user;
        User user = userDao.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        List<Role> rolesByUserId = userDao.getRolesByUserId(user.getId());
        user.setRoles(rolesByUserId);
        return user;
    }
}
